﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ymatou.ServiceCenter
{
    /// <summary>
    /// RPC客户端配置管理
    /// </summary>
    public static class RpcClientConfigManager
    {
        private static readonly SynchronizedDictionary<string, RpcClientConfig> Cache = new SynchronizedDictionary<string, RpcClientConfig>();
        private const int CacheTimeoutMinutes = 3;

        /// <summary>
        /// 获取RPC客户端配置文件
        /// </summary>
        /// <param name="appid">应用编号</param>
        /// <returns></returns>
        public static RpcClientConfig GetRpcClientConfig(string appid)
        {
            if (string.IsNullOrWhiteSpace(appid))
                throw new ArgumentNullException("appid");
            RpcClientConfig cfg = Cache.GetWithNoLock(appid);
            if (cfg == null)
            {
                lock (Cache.SyncRoot)
                {
                    cfg = Cache.GetWithNoLock(appid);
                    if (cfg == null)
                    {
                        cfg = ServiceCenterFacade.GetRpcClientCfg(appid);
                        cfg.CreateTime = DateTime.Now.AddMinutes(CacheTimeoutMinutes);
                        cfg.Check();
                        Cache.SetWithNoLock(appid, cfg);
                        Logger.Debug(string.Format("appid {0} 获取RpcClientConfig配置缓存值，过期时间 {1},cfg info:{2}"
                        , appid
                        , cfg.CreateTime,
                        cfg.ToString()));
                    }
                }
            }

            if (cfg.CreateTime < DateTime.Now)
            {
                Task.Factory.StartNew(() =>
                {
                    RpcClientConfig rpcClientConfig = ServiceCenterFacade.GetRpcClientCfg(appid);
                    cfg.CreateTime = DateTime.Now.AddMinutes(CacheTimeoutMinutes);
                    cfg.Check();
                    Cache[appid] = rpcClientConfig;
                    Logger.Debug(string.Format("appid {0} 刷新RpcClientConfig配置缓存值，过期时间 {1},cfg info:{2}"
                        , appid
                        , cfg.CreateTime,
                        cfg.ToString()));
                });
            }
            return cfg;

        }

        /// <summary>
        /// 当前客户端应用配置
        /// </summary>
        /// <returns></returns>
        public static RpcClientConfig GetCurrentClientConfig()
        {
            return GetRpcClientConfig(Utils.GetConsumerAppId());
        }

        /// <summary>
        /// 发送服务依赖的间隔时间（分钟）
        /// </summary>
        /// <returns></returns>
        public static TimeSpan GetSendServiceDependencyInterval()
        {
            return new TimeSpan(0, 0, GetCurrentClientConfig().SendDataDelayMinute, 0);
        }

        /// <summary>
        /// 获取自动更新服务元数据的更新时间（秒）
        /// </summary>
        /// <returns></returns>
        public static TimeSpan GetServiceMetadataAutoUpdateInterval()
        {
            return new TimeSpan(0, 0, 0, GetCurrentClientConfig().UpdateMetadataDelaySecond);
        }
    }
}
